<?php

namespace app\api\controller\coupons;
use addons\third\model\Third;
use app\common\library\Auth;
use app\common\library\Sms;
use fast\Http;
use think\Config;
use think\Validate;
use app\common\model\User as userc;
use think\Db;
use app\api\controller\coupons\Base;
use app\admin\model\coupons\Userstaff;
header('Access-Control-Allow-Origin:*');//允许跨域
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    header('Access-Control-Allow-Headers:x-requested-with,content-type,token');
    //浏览器页面ajax跨域请求会请求2次，第一次会发送OPTIONS预请求,不进行处理，直接exit返回，但因为下次发送真正的请求头部有带token
    //所以这里设置允许下次请求头带token否者下次请求无法成功
    exit();
}/**
 * 小程序接口列表
 */
class User extends Base
{
    protected $noNeedLogin = ['third', 'login', 'register', 'resetpwd', 'sendSmsVerify','createAutoCouponlists','getMyCouponListsByUID','getMyCouponCountByUID','getCouponDetails','getVerifyCoupon','getClinicLists','verifyClinicApply','subClinicApply','findNoUserClinic'];
    protected $noNeedRight = '*';
    protected $token = '';
    public function _initialize()
    {
            parent::_initialize();
            $this->user_id = $this->auth->id;
            $this->serverImgHost=($this->isHTTPS() ? 'https://' : 'http://') . $_SERVER['HTTP_HOST']; //获取域名
    }
    /**
     * ==第三方登录
     *
     * @param string $platform 平台名称
     * @param string $code     Code码
     */
    public function third()
    {
        $config = get_addon_config('coupons');
        $code = $this->request->post("code");
        $platform = $this->request->request("platform");
        $rawData=$this->request->request("raw_data");
        $rawData=str_replace('&quot;','"',$rawData);
        //和手机以及验证码一起注册
        // $mobile=$this->request->request("mobile")?$this->request->request("mobile"):'';
        // $captcha=$this->request->request("captcha")?$this->request->request("captcha"):'';
        //$group_id=$this->request->request("group_id")?$this->request->request("group_id"):'0';
        //$number=$this->request->request("number")?$this->request->request("number"):'';
        $rawData=json_decode($rawData,true);
        
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }

        $params = [
            'appid'      => $config[$platform]['app_id'],
            'secret'     => $config[$platform]['app_secret'],
            'js_code'    => $code,
            'grant_type' => 'authorization_code'
        ];

        $result = Http::sendRequest("https://api.weixin.qq.com/sns/jscode2session", $params, 'GET'); 
        //dump($result);exit;
        if ($result['ret']) {
            $json = (array)json_decode($result['msg'], true);
            //$json = ['openid' => 'test', 'session_key' => 'test'];
            if (isset($json['openid'])) {
                //如果有传Token
                if ($this->token) {

                    $this->auth->init($this->token);
                    //检测是否登录
                    if ($this->auth->isLogin()) {
                        $third = Third::where(['openid' => $json['openid'], 'platform' => 'wechat'])->find();
                        if ($third && $third['user_id'] == $this->auth->id) {
                            //把最新的 session_key 保存到 第三方表的 access_token 里
                            $third['access_token'] = $json['session_key'];
                            $third->save();
                            $this->success("登录成功", $this->Format_avatarUrl($this->auth->getUserinfo()));
                        }
                    }
                }
                //传手机号的情况下
                // if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
                //     $this->error(__('Mobile is incorrect'));
                // }
                // $ret = Sms::check($mobile, $code, 'register');
                // if (!$ret) {
                //     $this->error(__('Captcha is incorrect'));
                // }
                if(isset($json['unionid'])){
                    $unionid=$json['unionid']?$json['unionid']:''; 
                }else{
                    $unionid=''; 
                }
               
                $result = [
                        'openid'        => $json['openid'],
                        'unionid'        => $unionid,
                        'userinfo'      => [
                            'nickname'      => $rawData['nickName'],
                            'avatar'        => $rawData['avatarUrl'],
                            'gender'        => $rawData['gender'],
                           // 'mobile'        => $mobile
                                           ],
                    'access_token'      => $json['session_key'],
                    'refresh_token'     => '',
                    'expires_in'        => isset($json['expires_in']) ? $json['expires_in'] : 0,
                ];
                
                $loginret = \addons\third\library\Service::connect($platform, $result);
                $user = $this->auth->getUser();
                $user->nickname = $rawData['nickName'];
                $user->avatar = $rawData['avatarUrl'];
                $user->gender = $rawData['gender'];;
                $user->save();

                $auths = $this->auth->getUserinfo();
                $userInfo = $this->getUserInfo($auths['id']);

                $userinfos=[
                        'id'=>$userInfo['id'],
                        'username'=>$userInfo['username'],
                        'nickname'=>$userInfo['nickname'],
                        'mobile'=>$userInfo['mobile'],
                        'avatar'=>$userInfo['avatar'],
                        'token'=>$userInfo['token'],
                        'createtime'=>$userInfo['createtime'],
                        'group_id'=>$userInfo['group_id']
                ];

                if ($loginret) {
                    
                    $data = [
                        'userinfo'  =>$userInfo,
                        'thirdinfo' => $result,
                        'auth'      =>$auths

                    ];
                    $data['userinfo']['openid']=$data['thirdinfo']['openid'];
                    $data['userinfo']['unionid']=$data['thirdinfo']['unionid'];
                    
                    if ($auths) {
                        $this->success(__('Logged in successful'), $data);
                    } else {
                        $this->error($this->auth->getError());
                    }
                    
                }
                $this->error("登录失败");
                
            } else {
                $this->error("登录失败",$json);
            }
        }else{
             $this->error("请在微信中操作");
        }

        return;
    }
    /**
     * ==重置密码
     *
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
 
        $mobile = $this->request->request("mobile");
        $newpassword = $this->request->request("newpassword");
        $oldpassword = $this->request->request("oldpassword");
        if (!$newpassword || !$oldpassword) {
            $this->error(__('Invalid parameters'));
        }
  
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if (!$user) {
            $this->error(__('User not found'));
        }
        $ret = $this->auth->changepwd($newpassword, $oldpassword, false);
        if (!$ret) {
            $this->error(__('Password is incorrect'));
        }
       
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }
    /**
     * ==会员登录
     *
     * @param string $account  账号/手机或者密码或者用户名
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->request('account');
        $password = $this->request->request('password');
        //dump($password);
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        $userinfo=$this->auth->getUserinfo();
        if ($ret) {
             $data = ['userinfo' =>$userinfo,'auth' => $userinfo];
            $this->success(__('登录成功'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

     /**
     * ==返回我的角色，普通用户或员工
     */
    public function myGroup()
    {
        $user_id = $this->auth->id;
        if ($user_id) {
           $group_id=Db::name('user')->where('user_id',$user_id)->value('group_id'); 
          $this->success('', ['group_id' => $group_id]); 
        }else{
           $this->error("请重新登录");  
        }
    
    }
    
   
   /**
     * ==会员中心
     */
    public function index()
    {
    $user = $this->auth->getUser();
        $this->success('', ['data' => $user]);
    }

   /**
     * ==注销登录
     */
    public function logout()
    {
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * ==修改会员个人信息
     *
     * @param string $avatar   头像地址
     * @param string $birthday 生日
     * @param string $nickname 昵称
     * @param string $gender   个人性别
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $data = $this->request->request('');
    if(isset($data['avatar'])){
      $avatar = $this->request->request('avatar', '', 'trim,strip_tags,htmlspecialchars');
    }
        
        if (isset($data['username'])) {
            $exists = \app\common\model\User::where('username', $data['username'])->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $data['username'];
        }
        $data['birthday']=date('Y-m-d H:i:s',strtotime($data['birthday']));
        $user->nickname = $data['nickname'];
        $user->birthday = $data['birthday'];
        $user->realname = $data['realname'];
        $user->avatar = $data['avatar'];
        $user->bio = $data['bio'];
        $user->mobile = $data['mobile'];
        $user->gender = $data['sex'];
        $user->birthday = $data['birthday'];
        if(isset($data['avatar'])){
          $user->avatar = $avatar;
        }
        
        $user->save();

        $t=$this->thirdModel = new \addons\third\model\Third;        
        $t->allowField(true)->save(['openname'=>$data['nickname']],['user_id'=>$user['id']]);
        $this->success('修改成功');
    }

    /**
     * ==刷新用户
     * @throws \think\exception\DbException
     */
    public function refreshUser()
    {
        //var_dump($this->auth->isLogin());exit;
        if ($this->auth->isLogin()) {
            $auth = $this->auth->getUserinfo();
            $user = $this->getUserInfo($auth['user_id']);
            $data = ['auth' => $auth, 'user' => $user];
            $this->success(__('Refresh successful'), $data);
        } else {
            $this->error(__('Please login'));
        }
    }

    /**
     * ==获取非隐私用户信息
     * @param $id
     * @return User|null
     * @throws \think\exception\DbException
     */
    function getUserInfo($id)
    {
       
        $userinfo = userc::get($id);
        $userinfo->hidden(['maxsuccessions', 'updatetime', 'joinip', 'jointime', 'loginfailure', 'password', 'prevtime', 'salt', 'token', 'status']);
        //$userinfo['mobile'] = substr($userinfo['mobile'], 0, 3) . '****' . substr($userinfo['mobile'], -4);
        return $userinfo;
    }

  /**
     * ==绑定认证/积分商城普通用户或者员工
     *
     * @param string $mobile  手机
     * @param string $number   员工工号
     * @param string $group_id   申请的用户组，1普通用户，2员工
     * @param string $code   验证码
     */
    public function changeMobile()
    {
        $data = $this->request->request('');
        $mobile=$data['mobile'];
        $captcha=$data['captcha'];
        $group_id=$data['group_id'];
        $user_id=$this->user_id;
        $data['user_id']=$user_id;
        if (!$mobile || !$captcha || !$group_id) {
            $this->error(__('Invalid parameters'));
        }
        //员工绑定才会有工号
        if($group_id==2){
             $number=$data['number'];
             //$name=$data['name'];
         }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user_id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        //开启手机验证
        // $result = Sms::check($mobile, $captcha, 'changemobile');
        // if (!$result) {
        //     $this->error(__('Captcha is incorrect'));
        // }
        $isUserApply=Db::name('coupons_bind')->where('user_id',$data['user_id'])->where('group_id',$data['group_id'])->find();
        if($data['group_id']==1  && $isUserApply){ 
            $this->error('您已绑定过手机，无需再次绑定');
        }else if($data['group_id']==2 && $isUserApply){
           $this->error('您已通过员工认证，无需再次认证');
        }
        //判断如果是员工，对比导入的员工表，看是否有这条导入记录，如果有，且姓名和工号匹配，则验证通过。//->where('staffname',$data['name'])
        $res=true;
        if($data['group_id']==2){
            $isUserStaff=Db::name('coupons_user_staff')->where('staffnumber',$data['number'])->find();
            if(!$isUserStaff){
               $this->error('未查询到该员工信息，请确认填写信息是否有误'); 
            }else{
                $UserStaff=Userstaff::get($isUserStaff['id']);
                $UserStaff -> setAttr('user_id',$data['user_id']);
                $res=$UserStaff-> allowField(true)->save();
            }
        }
        unset($data['s']);
        unset($data['captcha']);
        unset($data['event']);
        $data['createtime']=time();
        $data['updatetime']=time();
        $userApply=Db::name('coupons_bind')->insertGetId($data);
        
        
      if($userApply && $res){
         $group_id=$data['group_id'];
         $user = $this->auth->getUser();
         $user->group_id = $group_id;
         $user->mobile = $data['mobile'];
         $verification = $user->verification;
         $verification->mobile = 1;
         $user->verification = $verification;
         if($data['group_id']==2 && $data['number']!=''){
          $user->staffnumber = $data['number'];  
         }
         $user->save();
         $this->success('绑定成功'); 
         // $dataLog = [
         //            'notice' =>$notice,
         //            'type'    =>0,//待审核
         //            'user_id'  =>$user_id,
         //            'user_type'  =>$data['userType'],
         //            'class_id'  =>$class_id,
         //            'createtime' =>time(),
         //            'status'=>0,
         //            'apply_id'=>$userApply
         //             ];
         //  $applyLog=Db::name('record_log')->insert($dataLog);
          // if($applyLog){
          //    $this->success('提交成功，请耐心等待审核结果');
          // }else{
          //   $this->error('申请失败，请重试');
          // }
      }else{
            $this->error('绑定失败，请重试');
          }
         
         
        
      }
    /**
     * ==发送验证码
     * @ApiMethod (POST)
     * @param string $mobile 手机号
     * @param string $event  事件名称
     * @return array|bool
     * @throws \think\Exception
     */
    public function sendSmsVerify()
    {
        $mobile = $this->request->request("mobile");
        $event = $this->request->request("event");

        if (!($mobile && $event)) {
            // 缺少参数
            $this->error(__('发送失败，请检查手机是否正确或稍后重试'));
        }
        //事件列表
        $eventarr = [
            'register',
            'resetpwd',
            'changemobile',
            'login',
            'changepwd'
        ];

        if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $last = Sms::get($mobile, $event);
        if ($last && time() - $last['createtime'] < 60) {
            $this->error(__('Frequent sending'));
        }
        $ipSendTotal = \app\common\model\Sms::where(['ip' => $this->request->ip()])->whereTime('createtime', '-1 hours')->count();
        if ($ipSendTotal >= 5) {
            $this->error(__('Frequent sendings'));
        }
        $userinfo = \app\common\model\User::getByMobile($mobile);
        if (!in_array($event, $eventarr)) {
            //无事件
            $this->error(__('Operation failed'));
        } elseif ($event == 'register' && $userinfo) {
            //已被注册
            $this->error(__('Username already exist'));
        } elseif (in_array($event, ['changemobile']) && $userinfo) {
            //被占用
            $this->error(__('Mobile already exist'));
        } elseif (in_array($event, ['changepwd', 'resetpwd']) && !$userinfo) {
            //未注册
            $this->error(__('Account not exist'));
        }else if(in_array($event, ['login', 'resetpwd']) && !$userinfo){
            $this->error(__('手机号不存在，请先注册'));
        }
        $ret = Sms::send($mobile, null, $event);
        //$ret = true;
        if ($ret) {
            $this->success(__('Send successful'));
        } else {
            $this->error(__('Send failed'));
        }
    }
     /**
     * ==修改手机号
     *
     * @param string $mobile   手机号
     * @param string $captcha 验证码
     */
    // public function changeMobile()
    // {
    //     $user = $this->auth->getUser();
    //     //var_dump($user);exit;
    //     $mobile = $this->request->request('mobile');
    //     $captcha = $this->request->request('captcha');
    //     $gropu_id = $this->request->request('group_id');
    //     if (!$mobile || !$captcha || !$gropu_id) {
    //         $this->error(__('Invalid parameters'));
    //     }
    //     if (!Validate::regex($mobile, "^1\d{10}$")) {
    //         $this->error(__('Mobile is incorrect'));
    //     }
    //     if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
    //         $this->error(__('Mobile already exists'));
    //     }
    //     $result = Sms::check($mobile, $captcha, 'changemobile');
    //     if (!$result) {
    //         $this->error(__('Captcha is incorrect'));
    //     }
    //     //$results =Db::name('user')->where('');
    //     $verification = $user->verification;
    //     $verification->mobile = 1;
    //     $user->verification = $verification;
    //     $user->mobile = $mobile;
    //     $user->save();

    //     Sms::flush($mobile, 'changemobile');
    //     $this->success();
    // }

   


      /**
     * ==获取我的预约和订单数量
     * @param $str
     * @return mixed
     */
    public function getMyData()
    {
          $type=$this->request->request('type');
          $page=$this->request->request('page')?$this->request->request('page'):'';
          $limit=$this->request->request('limit')?$this->request->request('limit'):'';
          if($type==2 || $type==3){
             $myData=$this->myData($type,$page,$limit);
          }else{
             $myData=$this->myData();
          }
        if($myData){
            $this->success('获取成功',$myData);
        }else{
           $this->error('获取失败，请重试'); 
        }
         
        }
  
      /**
     * ==我的优惠券--数量
     * @param $str
     * @return mixed
     */
    public function getMyCouponCount()
    {
      //$statusdata=$this->request->request('statusdata')?$this->request->request('statusdata'):0;
      $MyCouponCount=$this->myCouponCount();
      if($MyCouponCount){
            $this->success('获取成功',$MyCouponCount);
        }else{
           $this->error('获取失败，请重试'); 
        }   
    } 

     /**
     * ==我的优惠券--数量
     * @param $str
     * @return mixed
     */
    public function getMyCouponCountByUID()
    {
      $uid=$this->request->request('uid');
      $MyCouponCount=$this->myCouponCountByUID($uid);
      if($MyCouponCount){
            $this->success('获取成功',$MyCouponCount);
        }else{
           $this->error('获取失败，请重试'); 
        }   
    } 
  /**
     * ==我的优惠券--列表
     * @param string $type -1代表全部，0代表未使用，1代表已预约,2代表已完成 
     * @param string $page 页数
     * @param string $limit 每页数量
     */
    public function getMyCouponLists()
    {
       $type=$this->request->request('type');
       $page=$this->request->request('page')?$this->request->request('page'):0;
       $limit=$this->request->request('limit')?$this->request->request('limit'):10;
       $getMyCouponLists=$this->myCouponLists($type,$page,$limit); 
       //获取clinic_id这一列数据
       $couponListsIds=array_column($getMyCouponLists, 'clinic_id');
       //去除为0的
       $couponListsIds=array_diff($couponListsIds, [0]);
       //去重
       $couponListsIds=array_unique( $couponListsIds);
       //键值重新排序
       $couponListsIds=array_values($couponListsIds);
       $couponListsInfo=Db::name('coupons_clinic')->where('id','in',$couponListsIds)->select();
       //var_dump( $couponListsInfo);exit;
       $serverImgHost=$this->serverImgHost;
       //C.name as clinic_name,C.addresstext,C.longitudetext,C.latitudetext,C.phonetext,C.logoavatar,C.coverpicimages as clinci_images,C.qrcodeimage, 
       foreach ($getMyCouponLists as $key => $value) {
            $getMyCouponLists[$key]['begintime']=date('Y-m-d',strtotime($value['begintime']));
            if($value['appointmenttime']){
               $getMyCouponLists[$key]['appointmenttime']=date('Y-m-d H:00',$value['appointmenttime']); 
               }else{
                $getMyCouponLists[$key]['appointmenttime']='';
               }
             if($value['finishtime']){
               $getMyCouponLists[$key]['finishtime']=date('Y-m-d H:00',$value['finishtime']); 
               }else{
                $getMyCouponLists[$key]['finishtime']='';
               }
            $getMyCouponLists[$key]['endtime']=date('Y-m-d',strtotime($value['endtime']));
            $getMyCouponLists[$key]['coverpicimage']=$serverImgHost.$value['coverpicimage'];
            $getMyCouponLists[$key]['qrcodeimage']=$serverImgHost.$value['qrcodeimage'];
            $getMyCouponLists[$key]['clinic']=[];
            foreach ($couponListsInfo as $k => $v) {
                if($value['clinic_id']==$couponListsInfo[$k]['id']){
                    $couponListsInfo[$k]['logoavatar']= $serverImgHost.$v['logoavatar'];
                    $couponListsInfo[$k]['coverpicimages']= $serverImgHost.$v['coverpicimages'];
                    $couponListsInfo[$k]['qrcodeimage']= $serverImgHost.$v['qrcodeimage'];
                    $getMyCouponLists[$key]['clinic']=$couponListsInfo[$k];
                }
            }
        } 
       $this->success('获取成功',$getMyCouponLists);
    } 

    /**
     * ==我的优惠券--列表
     * @param string $type -1代表全部，0代表未使用，1代表已预约,2代表已完成 
     * @param string $page 页数
     * @param string $limit 每页数量
     */
    public function getMyCouponListsByUID()
    {    
       $type=$this->request->request('type');
       $uid=$this->request->request('uid');
       $page=$this->request->request('page')?$this->request->request('page'):0;
       $limit=$this->request->request('limit')?$this->request->request('limit'):10;
       $getMyCouponLists=$this->myCouponListsByUID($uid,$type,$page,$limit); 
       //获取clinic_id这一列数据
       $couponListsIds=array_column($getMyCouponLists, 'clinic_id');
       //去除为0的
       $couponListsIds=array_diff($couponListsIds, [0]);
       //去重
       $couponListsIds=array_unique( $couponListsIds);
       //键值重新排序
       $couponListsIds=array_values($couponListsIds);
       $couponListsInfo=Db::name('coupons_clinic')->where('id','in',$couponListsIds)->select();
       //var_dump( $couponListsInfo);exit;
       $serverImgHost=$this->serverImgHost;
       //C.name as clinic_name,C.addresstext,C.longitudetext,C.latitudetext,C.phonetext,C.logoavatar,C.coverpicimages as clinci_images,C.qrcodeimage, 
       foreach ($getMyCouponLists as $key => $value) {
            $getMyCouponLists[$key]['begintime']=date('Y-m-d',strtotime($value['begintime']));
            if($value['appointmenttime']){
               $getMyCouponLists[$key]['appointmenttime']=date('Y-m-d H:00',$value['appointmenttime']); 
               }else{
                $getMyCouponLists[$key]['appointmenttime']='';
               }
             if($value['finishtime']){
               $getMyCouponLists[$key]['finishtime']=date('Y-m-d H:00',$value['finishtime']); 
               }else{
                $getMyCouponLists[$key]['finishtime']='';
               }
            $getMyCouponLists[$key]['endtime']=date('Y-m-d',strtotime($value['endtime']));
            $getMyCouponLists[$key]['coverpicimage']=$serverImgHost.$value['coverpicimage'];
            $getMyCouponLists[$key]['qrcodeimage']=$serverImgHost.$value['qrcodeimage'];
            $getMyCouponLists[$key]['clinic']=[];
            foreach ($couponListsInfo as $k => $v) {
                if($value['clinic_id']==$couponListsInfo[$k]['id']){
                    $couponListsInfo[$k]['logoavatar']= $serverImgHost.$v['logoavatar'];
                    $couponListsInfo[$k]['coverpicimages']= $serverImgHost.$v['coverpicimages'];
                    $couponListsInfo[$k]['qrcodeimage']= $serverImgHost.$v['qrcodeimage'];
                    $getMyCouponLists[$key]['clinic']=$couponListsInfo[$k];
                }
            }
        } 
       $this->success('获取成功',$getMyCouponLists);
    } 
    /**
     * ==优惠券--详情
     * @param string $id 优惠券id
     * @param string $number  优惠券编码
     * @param string $type type=0,代表是自己查看，type=1代表是扫码工作人员查看
     */
    public function getCouponDetails()
    {
       $coupon_id=$this->request->request('id');
       $coupon_number=$this->request->request('number');
       $type=$this->request->request('type')?$this->request->request('type'):0;
       $types=array(0,1);
       if(!in_array($type,$types)){
        $this->error(__('Invalid parameters'));
       }
       $couponDetails=$this->couponDetails($coupon_id,$coupon_number,$type);  
       if($couponDetails){
           $serverImgHost=$this->serverImgHost;
           $couponDetails['qrcodeimage']=$serverImgHost.$couponDetails['qrcodeimage'];
           $couponDetails['coupon_category_id']['coverpicimage']=$serverImgHost.$couponDetails['coupon_category_id']['coverpicimage'];
           $couponDetails['appointmenttime']=date('Y年m月d日 H:i',$couponDetails['appointmenttime']);
           $couponDetails['begintime']=date('Y年m月d日',$couponDetails['begintime']);
            $couponDetails['endtime']=date('Y年m月d日',$couponDetails['endtime']);
            $this->success('获取成功',$couponDetails);
       }else{
           $this->error('获取失败，请重试'); 
       }  
    }
 /**
     * ==门店基本信息
     *
     * @param string $id           门店id
     */
    public function getCouponProfile()
    {
        $user_id = $this->user_id;
        $id = $this->request->request('id')?$this->request->request('id'):'';
        if(!$id){
                $this->error(__('Invalid parameters'));
               }
        //管理员角色才可以编辑对应门店的基本信息。
        $isClinicAdmin=$this->isClinicStaff($user_id,$id,0);
        $couponInfo=Db::name('coupons_clinic')
                    ->where('id',$id)
                    ->find();        
     if($couponInfo){
        $serverImgHost=$this->serverImgHost;
        $couponInfo['logoavatar']= $serverImgHost.$couponInfo['logoavatar']; 
           $this->success('获取成功',$couponInfo); 
      }else{
           $this->error('获取失败，请重试'); 
       }  
        
    }
 /**
     * ==修改门店基本信息
     *
     * @param string $logoavatar   头像地址
     * @param string $id           门店id
     * @param string $name         门店名称
     * @param string $phonetext    门店电话
     * @param string $adresstext   地址
     * @param string $longtitude   经度
     * @param string $latitude     纬度
     * @param string $province     省
     * @param string $city         市
     * @param string $area         区
     */
    public function couponProfile()
    {
        $user_id = $this->user_id;
        $data = $this->request->request('');
        if(!$data['id']){
                $this->error(__('Invalid parameters'));
               }
        //管理员角色才可以编辑对应门店的基本信息。
        $isClinicAdmin=$this->isClinicStaff($user_id,$data['id'],1);
        if(isset($data['logoavatar'])){
          $data['logoavatar'] = $this->request->request('logoavatar', '', 'trim,strip_tags,htmlspecialchars');
          $data['logoavatar'] =ltrim(parse_url($data['logoavatar'],PHP_URL_PATH));
        }
        /*
        $pname=$data['province'];
        $cname=$data['city'];
        $aname=$data['area'];
         if($data['province']){
            $data['province']=Db::name('area')->where(['name'=>$pname,'pid'=>0])->whereOr('id',$pname)->value('id');
            if($data['city']){
                $data['city']=Db::name('area')->where(['name'=>$cname,'pid'=>$data['province']])->whereOr('id',$cname)->value('id');
                if($data['area']){
                $data['area']=Db::name('area')->where(['name'=>$aname,'pid'=>$data['city']])->whereOr('id',$aname)->value('id');
               }else{
                $this->error('地址查询失败-3');
               } 
           }else{
               $this->error('地址查询失败-2');
           }
          
        }else{
              $this->error('地址查询失败-1');  
        }*/
              
        $clinic = new  \app\admin\model\coupons\Clinic();
         try { 
              $resc=$clinic->allowField(true)->save($data,['id' =>$data['id']]);
                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
            } catch (PDOException $e) {
                Db::rollback();
            } catch (Exception $e) {
                Db::rollback();
            }
           $this->success('修改成功'); 
      
        
    }
   /**
     * ==获取我的单条预约详情
     *  @param string $coupon_id
     *  @param string $id
     */
    public function getOneAppointment()
    {
           $coupon_id=$this->request->request('coupon_id')?$this->request->request('coupon_id'):'';
           $id=$this->request->request('id')?$this->request->request('id'):'';
           if(!$coupon_id || $coupon_id==''){
                $this->error(__('Invalid parameters'));
               }
           $user_id=$this->user_id;
           if($id){
            $coupon_appointment=Db::name('coupons_appointment')
                              ->alias('A')
                              ->join('coupons_clinic B','A.clinic_id = B.id')
                              ->where(['A.id'=>$id])
                              ->field("A.id,A.user_id,A.realname,A.phonetext,A.coupon_id,from_unixtime(A.appointmenttime,'%Y年%m月%d日%H时') as appointmenttime,A.clinic_id,A.contenttext,A.statuslist,B.name")
                              ->find();
           } 
           //var_dump($coupon_appointment);exit;
           $coupon_info=Db::name('coupons')->where(['id'=>$coupon_id])->field('coupon_category_id,begintime,endtime')->find();
           $coupon_appointment['coupon_begintime']=date('Y-m-d H:i',$coupon_info['begintime']);
           $coupon_appointment['coupon_endtime']=date('Y-m-d H:i',$coupon_info['endtime']);
           $coupon_appointment['coupon_name']=Db::name('coupons_category')->where(['id'=>$coupon_info['coupon_category_id']])->value('nametext');
       
          $this->success('获取成功',$coupon_appointment);
     
         
        } 
    /**
     * ==获取我的预约列表，门店的预约列表
     *  @param string $type   1代表用户，2代表门店员工
     *  @param string $clinic_id   type=2的时候必传
     *  @param string $page   页数
     *  @param string $limit  每页数量
     */
    public function getMyAppointment()
    {        
          $type=$this->request->request('type')?$this->request->request('type'):'';
          $clinic_id=$this->request->request('clinic_id')?$this->request->request('clinic_id'):'';
          $page=$this->request->request('page')?$this->request->request('page'):'';
          $limit=$this->request->request('limit')?$this->request->request('limit'):'';
          if(!$type){
                $this->error(__('Invalid parameters'));
               }
          $myAppointment=$this->myAppointment($type,$clinic_id,$page,$limit);
          $this->success('获取成功',$myAppointment);
     
         
        } 
   /**
     * ==提交/修改预约门店信息【门店员工修改或者审核预约信息】
     *  @param string $id  
     *  @param string $type     角色类型，1代表自己，2代表门店
     *  @param string $phonetext  预约手机号
     *  @param string $appointmenttime  预约时间
     *  @param string $contenttext  备注
     *  @param string $coupon_id  优惠券id
     *  @param string $realname  真实姓名
     *  @param string $clinic_id  门店id
     *  @param string $statuslist  预约状态:0=已提交-默认值,1=门店通过预约,2=门店审核预约失败
     *  @param string $all  代表返回全部的优惠券数据，不需要传此值
     */
    public function getSubAppointment()
    {     
          $id=$this->request->request('id')?$this->request->request('id'):'';
          $type=$this->request->request('type')?$this->request->request('type'):1;
          $phonetext=$this->request->request('phonetext');
          $appointmenttime=$this->request->request('appointmenttime');
          $contenttext=$this->request->request('contenttext');
          $coupon_id=$this->request->request('coupon_id');
          $realname=$this->request->request('realname');
          $clinic_id=$this->request->request('clinic_id');
          $statuslist=$this->request->request('statuslist')?$this->request->request('statuslist'):0;
          //var_dump($statuslist);exit;
          $user_id=$this->user_id; 
          if(!$phonetext || !$realname || !$clinic_id || !$appointmenttime ||!$coupon_id){
            $this->error(__('Invalid parameters')); 
          }
          $couponStatus=Db::name('coupons')->where('id',$coupon_id)->field('begintime,endtime,statusdata')->find();

          if(!$couponStatus || $couponStatus['statusdata']==null || $couponStatus['statusdata']==''){
                 $this->error(__('该优惠券不存在')); 
            }
            if($couponStatus['statusdata']==2){
                 $this->error(__('该优惠券已使用，无法再次预约')); 
            }
            if($couponStatus['statusdata']==3){
                 $this->error(__('该优惠券已过期')); 
            }
            if($couponStatus['statusdata']==4){
                 $this->error(__('该优惠券已作废')); 
            }
           //$appointmenttime=strtotime($appointmenttime);
           $arr = date_parse_from_format('Y年m月d日h时',$appointmenttime);
           $appointmenttime = mktime($arr['hour'],0,0,$arr['month'],$arr['day'],$arr['year']);//mktime(hour,minute,second,month,day,year,is_dst);
           //var_dump(date('Y-m-d H',$appointmenttime));exit;
           if($couponStatus['begintime']>$appointmenttime || $couponStatus['endtime']<$appointmenttime){
                 $this->error(__('预约时间不在该优惠券有效期内')); 
            }
           $datas=[
                'phonetext'=>$phonetext,
                'appointmenttime'=>$appointmenttime,
                'contenttext'=>$contenttext,
                'realname'=>$realname,
                'clinic_id'=>$clinic_id,
                'coupon_id'=>$coupon_id,
                'user_id'=>$user_id,
             ];
         $rescou=1;
          $appointment = new \app\admin\model\coupons\Appointment();
          if($type==1){
                  //角色是优惠券所有者
                  //查询我的所有优惠券记录
                  $myCouponLists=$this->myCouponLists(-1,'','',1);
                  $myCouponListsIds=array_column($myCouponLists,'id');
                  

                  if(!in_array($coupon_id, $myCouponListsIds)){
                     $this->error(__('您的账户未查询到此优惠券'));
                  }
                  
                if($id){

                          try { 
                                  $resc=$appointment->allowField(true)->save($datas,['id' =>$id]);
                                    Db::commit();
                                } catch (ValidateException $e) {
                                    Db::rollback();
                                } catch (PDOException $e) {
                                    Db::rollback();
                                } catch (Exception $e) {
                                    Db::rollback();
                                }
                }else{
                    $hasAppointment=Db::name('coupons_appointment')->where(['coupon_id'=>$coupon_id,'user_id'=>$user_id,'statuslist'=>array('neq',2)])->find(); 
                    if($hasAppointment){
                      $this->error(__('您已提交过该优惠券的预约，请不要重复预约')); 
                    }
                     $appointment = new \app\admin\model\coupons\Appointment();
                          try { 
                                  $resc=$appointment->allowField(true)->save($datas);
                                    Db::commit();
                                } catch (ValidateException $e) {
                                    Db::rollback();
                                } catch (PDOException $e) {
                                    Db::rollback();
                                } catch (Exception $e) {
                                    Db::rollback();
                                }
                } 
        }else{
            //门店员工
                if(!$id){
                  $this->error(__('Invalid parameters'));   
                }
                 //判断是否是门店员工或者管理员
                $datas['statuslist']=$statuslist;
                $coupon_staffs=$this->isClinicStaff($user_id,$clinic_id);
                try { 
                                  $resc=$appointment->allowField(true)->save($datas,['id' =>$id]);
                                    Db::commit();
                                } catch (ValidateException $e) {
                                    Db::rollback();
                                } catch (PDOException $e) {
                                    Db::rollback();
                                } catch (Exception $e) {
                                    Db::rollback();
                                }
            //门店审核通过，才将预约信息插入到优惠券记录里
            
             if($statuslist==1){
                   $datam['statusdata']=1;
                   $datam['appointmenttime']=$appointmenttime;
                   $datam['clinic_id']=$clinic_id; 
                   $coupon = new \app\admin\model\coupons\Coupons();
                   try { 
                                          $rescou=$coupon->allowField(true)->save($datam,['id' =>$coupon_id]);
                                            Db::commit();
                                        } catch (ValidateException $e) {
                                            Db::rollback();
                                        } catch (PDOException $e) {
                                            Db::rollback();
                                        } catch (Exception $e) {
                                            Db::rollback();
                                        } 
                }
               
        }
        

        if($resc && $rescou){
            $this->success('预约成功');
        }else{
           $this->error('获取失败，请重试'); 
        }
         
        } 
 /**
     * ==获取门店订单列表
     *  @param string $clinic_id   门店id
     *  @param string $type   员工列表状态 全部-1 是否授权:0=等待授权,1=已授权,2=拒绝授权
     *  @param string $page   页数
     *  @param string $limit  每页数量
     */
    public function getOrders()
    {
          $clinic_id=$this->request->request('clinic_id');
          $page=$this->request->request('page')?$this->request->request('page'):'1';
          $limit=$this->request->request('limit')?$this->request->request('limit'):'10';
          if(!$clinic_id){
            $this->error(__('Invalid parameters')); 
          }
         //判断是否是门店员工或者管理员
         $user_id=$this->user_id; 
         $coupon_staffs=$this->isClinicStaff($user_id,$clinic_id);
         $mygetOrders=Db::name('coupons_order')
                    ->alias('A')
                    ->join('coupons_clinic B','A.coupon_clinic_id = B.id')
                    ->join('coupons_category C','A.coupon_category_id = C.id')                   
                    ->where('A.coupon_clinic_id',$clinic_id)
                    ->field("A.*,B.name as clinic_name,B.addresstext,B.phonetext as appointment_phone,B.user_id,C.nametext as coupon_nanme,C.pricenumber as coupon_price,C.pricenumber")
                    ->order('finishtime desc')
                    ->page($page,$limit)
                    ->select();
        foreach ($mygetOrders as $key => $value) {
           $mygetOrders[$key]['finishtime']=date('Y-m-d H:i',$value['finishtime']);
        }
        $this->success('获取成功',$mygetOrders);
        } 
      /**
     * ==获取门店员工列表
     *  @param string $clinic_id   门店id
      *  @param string $authorizedata   审核状态是否授权:0=等待授权,1=已授权,2=拒绝授权
     *  @param string $page   页数
     *  @param string $limit  每页数量
     */
    public function getClinicStaff()
    {     $clinic_id=$this->request->request('clinic_id');
          $authorizedata=$this->request->request('authorizedata')?$this->request->request('authorizedata'):'';
          $page=$this->request->request('page')?$this->request->request('page'):'';
          $limit=$this->request->request('limit')?$this->request->request('limit'):'';
          if(!$clinic_id){
            $this->error(__('Invalid parameters')); 
          }
          $where['coupon_clinic_id']=$clinic_id;
          if($authorizedata==0 || $authorizedata==1 || $authorizedata==2){
            $where['authorizedata']=$authorizedata;
          }
          //判断是否是门店员工或者管理员
          $user_id=$this->user_id; 
          $coupon_staffs=$this->isClinicStaff($user_id,$clinic_id);
          $clinicStaff=Db::name('coupons_clinic_staff')
                    ->where($where)
                    ->field("id,nametext,user_id,coupon_clinic_id,clinicnametext,authorizedata,reasontext,from_unixtime(createtime,'%Y-%m-%d %H:%i') as createtime")
                    ->order('id desc')
                    ->page($page,$limit)
                    ->select();
         $this->success('获取成功',$clinicStaff);
       
         
        } 
     /**
     * ==审核员工加入门店
     *  @param string $id    提交加入门店的员工申请id
     *  @param string $clinic_id    门店的id
     *  @param string $status  1代表授权 2代表拒绝授权 3代表删除该条记录
     */
    public function getverifyStaff()
    {     $id=$this->request->request('id');
          $clinic_id=$this->request->request('clinic_id');
          $status=$this->request->request('status');
            if(!$id || !$status){
                $this->error(__('Invalid parameters')); 
              }
          //判断是否是门店员工或者管理员
          $user_id=$this->user_id; 
          $data['authorizedata']=$status;
          $coupon_staffs=$this->isClinicStaff($user_id,$clinic_id);
          if($status==1 || $status==2){
            $clinicStaff=Db::name('coupons_clinic_staff')
                    ->where('id',$id)
                    ->update($data);
        }else if($status==3){
                    $clinicStaff=Db::name('coupons_clinic_staff')
                                        ->where('id',$id)
                                        ->delete();
        }else{
            $this->error(__('Invalid parameters')); 
        }
          
        if($clinicStaff){
            $this->success('操作成功！');
        }else{
           $this->error('操作失败，请重试'); 
        }
         
        } 
    /**
     * ==门店--列表
     *  @param string $id     优惠券id
     *  @param string $lat    当前用户的纬度
     *  @param string $lng    当前用户的经度
     *  @param string $order  排序规则
     *  @param string $page   页数
     *  @param string $limit  每页数量
     *  @param string $province  省份id
     *  @param string $city  城市id
     *  @param string $area  区域id
     */
    public function getClinicLists()
    {
       $coupon_id=$this->request->request('id');
       $page=$this->request->request('page')?$this->request->request('page'):0;
       $limit=$this->request->request('limit')?$this->request->request('limit'):10;
       $order=$this->request->request('order')?$this->request->request('order'):'weigh desc,id asc';
       $lat=$this->request->request('latitude')?$this->request->request('latitude'):'';
       $lng=$this->request->request('longitude')?$this->request->request('longitude'):'';
       $province=$this->request->request('province')?$this->request->request('province'):'';
       $city=$this->request->request('city')?$this->request->request('city'):''; 
       $area=$this->request->request('area')?$this->request->request('area'):'';  

        if(!$coupon_id){
         $this->error(__('Invalid parameters'));
       }
       $clinicLists=$this->clinicLists($coupon_id,$page,$limit,$order,$province,$city,$area,$lat,$lng);  
       if($clinicLists['near']){
           $serverImgHost=$this->serverImgHost;
           foreach ($clinicLists['near'] as $key => $value) {
                if($value['logoavatar']!=''){
                      $clinicLists['near'][$key]['logoavatar']=$serverImgHost.$value['logoavatar'];
                }else{
                      $clinicLists['near'][$key]['logoavatar']=$serverImgHost.'/uploads/default.png'; 
                }
               
           }  
       }else{
               $clinicLists['near']=[];
       }
       //获取所有列表
       if($clinicLists['lists']){
           $serverImgHost=$this->serverImgHost;
           foreach ($clinicLists['lists'] as $key => $value) {
                if($value['logoavatar']!=''){
                        $clinicLists['lists'][$key]['logoavatar']=$serverImgHost.$value['logoavatar'];
                }else{
                        $clinicLists['lists'][$key]['logoavatar']=$serverImgHost.'/uploads/default.png'; 
                }
           }  
       }else{
           $clinicLists['lists']=[];
       } 
         $this->success('获取成功',$clinicLists); 
    } 
    /**
     * ==门店个人中心+用户+数据
     */
    public function getMyClinicInfo()
    {  
       $user_id=$this->user_id;
       // if(!$coupon_number || !$coupon_id){
       //   $this->error('参数错误'); 
       // }
       $getMyClinicInfo=$this->myClinicInfo();  
        if($getMyClinicInfo){
            if($getMyClinicInfo['user_type']==0){
                $this->error("您不是门店管理员或员工"); 
            }else{
                $serverImgHost=$this->serverImgHost;
                $getMyClinicInfo['qrcodeimage']=$serverImgHost.$getMyClinicInfo['qrcodeimage']; 
                
                $this->success("ok",$getMyClinicInfo); 
            }
            
         }else{
            $this->error(""); 
         }
    } 
    /**
     * ==门店人员--核销优惠券接口
     * @param string $number 优惠券编码
     * @param string $updateThird 更新三方  1  有unionid 已更新，0 无需更新，直接改优惠券状态
     */
    public function getVerifyCoupon()
    {
       //$coupon_id=$this->request->request('id');
       $coupon_number=$this->request->request('number');
       $updateThird=$this->request->request('updateThird')?$this->request->request('updateThird'):0;
       if(!$coupon_number){
         $this->error('参数错误'); 
       }
       $verifyCoupon=$this->verifyCoupon($coupon_number,$updateThird);  
       
    }

    /**
     * ==员工扫码验证是否已经提交以及提交状态
     *@param string $coupon_clinic_id 门店id
     */
    public function isClinicApply(){
        $data['coupon_clinic_id']=$this->request->request('coupon_clinic_id')?$this->request->request('coupon_clinic_id'):'';
        $data['user_id']=$this->auth->id;
        if(!$data['coupon_clinic_id']){
           $this->error(__('Invalid parameters')); 
        }
        $isSub=Db::name('coupons_clinic_staff')
              ->where(['user_id'=>$data['user_id'],'coupon_clinic_id'=>$data['coupon_clinic_id']])
              ->find();
        
        if($isSub){
            if($isSub['authorizedata']==0){
               $this->success("您已提交申请,请等待门店审核",['code'=>0,'reason'=>$isSub['reasontext']]);   
           }else if($isSub['authorizedata']==1){
                $this->success("您的审核已通过，已成为门店员工",['code'=>1,'reason'=>$isSub['reasontext']]); 
           }else{
               $this->success("抱歉，您的申请已拒绝，请联系门店或重新申请",['code'=>2,'reason'=>$isSub['reasontext']]); 
           }
          
        }else{
              $this->success("暂未申请",['code'=>3,'reason'=>$isSub['reasontext']]); 
        }
         
    }

     /**
     * ==员工扫码加入门店申请
     * @param string $coupon_clinic_id 门店id
     * @param string $nametext 用户真实姓名
     */
    public function subClinicApply(){
        $data['coupon_clinic_id']=$this->request->request('coupon_clinic_id')?$this->request->request('coupon_clinic_id'):'';
        $data['nametext']=$this->request->request('nametext')?$this->request->request('nametext'):'';
        $data['user_id']=$this->auth->id;
        $data['createtime']=time();
        $data['updatetime']=time();
        if(!$data['coupon_clinic_id'] || !$data['nametext']){
           $this->error(__('Invalid parameters')); 
        }
        $isSub=Db::name('coupons_clinic_staff')
              ->where(['user_id'=>$data['user_id'],'coupon_clinic_id'=>$data['coupon_clinic_id']])
              ->find();
       
     if($isSub){
            if($isSub['authorizedata']==0){
               $this->error("您已提交申请，在审核结束前，请勿重复提交"); 
            }
             if($isSub['authorizedata']==1){
               $this->error("您的审核已通过，已成为门店员工"); 
            }
            if($isSub['authorizedata']==2){
               $res=Db::name('coupons_clinic_staff')
                                  ->where(['id'=>$isSub['id']])
                                  ->delete(); 
            }
        }
        $data['clinicnametext']=Db::name('coupons_clinic')
                              ->where(['id'=>$data['coupon_clinic_id']])
                              ->value('name');
         $subClinicApply=Db::name('coupons_clinic_staff')->insertGetId($data);
         if($subClinicApply){
            $this->success("提交成功，请等待门店审核"); 
         }else{
            $this->error("申请失败，请重试"); 
         }
    }

      /**
     * ==门店管理员审核员工加入门店
     * @param string $authorizedata 是否授权:0=等待授权,1=已授权,2=拒绝授权
     * @param string $reasontext 审核原因
     * @param string $id 申请条目的id
     */
    public function verifyClinicApply(){
        $user_id=$this->auth->id;
        $data['authorizedata']=$this->request->request('authorizedata')?$this->request->request('authorizedata'):'';
        $data['reasontext']=$this->request->request('reasontext')?$this->request->request('reasontext'):'';
        $data['id']=$this->request->request('id')?$this->request->request('id'):'';
        if(!$data['authorizedata'] || !$data['id']){
           $this->error(__('Invalid parameters')); 
        }
        $clinic_admin=Db::name('coupons_clinic_staff')
                    ->alias('A')
                    ->join('coupons_clinic B', 'A.coupon_clinic_id = B.id')
                    ->where('A.id',$data['id'])
                    ->value('B.user_id');

        if(!$clinic_admin){
            $this->error("该门店未绑定管理员");  
        }elseif($user_id!=$clinic_admin){
            $this->error("您不是该门店管理员，无法审核"); 
        }
        $datas=['authorizedata'=>$data['authorizedata'],
                'updatetime'=>time(),
                'reasontext'=>$data['reasontext'],
                ];
         $verifyClinicApply=Db::name('coupons_clinic_staff')->where('id',$data['id'])->update($datas);
         if($verifyClinicApply){
            $this->success("审核成功"); 
         }else{
            $this->error("申请失败，请重试"); 
         }
    }
    /**
     * ==关键字查询门店
     * @param string $keywords  门店关键字
     */
    public function findNoUserClinic(){
        
        $keywords=$this->request->request('keywords');
        if($keywords=='' || !isset($keywords)){
             $this->error("请输入关键字"); 
        }
        $where['name'] =array('like', "%".$keywords."%");
        $where['user_id']=array('eq',0);
        $clinic_lists=Db::name('coupons_clinic')
                    ->where($where)
                    ->select();
        $this->success("查询成功",$clinic_lists); 
    }
     /**
     * ==申请认领系统中的门店。
     * @param string $user_name 申请人姓名
     * @param string $user_mobile 申请人手机
     * @param string $clinic_id 门店id
     */
    public function applyMyClinic(){
        
        $data=$this->request->request();
        if(!$data['user_name'] || !$data['user_mobile'] || !$data['clinic_id']){
           $this->error(__('Invalid parameters')); 
        }
        $data['user_id']=$this->auth->id;
        $clinic_info=Db::name('coupons_clinic')
                    ->where('id',$data['clinic_id'])
                    ->field('name')
                    ->find();
        if(!empty($clinic_info)){
            $data['clinic_name']=$clinic_info['name'];
        }else{
             $this->error("未查询到该门店，请重试"); 
        }
        $clinic_info_apply=Db::name('coupons_apply')
                    ->where(['clinic_id'=>$data['clinic_id'],'apply_statuslist'=>1])
                    ->find();
        if(!empty($clinic_info_apply)){
            $this->error("该门店已绑定管理员，请重新选择"); 
        }

        $data['updatetime']=time();
        $data['createtime']=time();
        $verifyClinicApply=Db::name('coupons_apply')->insert($data);
         if($verifyClinicApply){
            $this->success("提交成功，请等待系统审核"); 
        }else{
            $this->error("申请失败，请重试"); 
        }
    }

    /**
     * ==绑定门店管理员
     * @param string $user_name 申请人姓名
     * @param string $user_mobile 申请人手机
     * @param string $user_code 门店编码
     * @param string $user_password 门店密码
     */
    public function bindMyClinic(){
        
        $data=$this->request->request();
        if(!$data['user_name'] || !$data['user_mobile'] || !$data['user_code'] || !$data['user_password']){
           $this->error(__('Invalid parameters')); 
        }
        $data['user_id']=$this->auth->id;
        $clinic_info=Db::name('coupons_clinic')
                    ->where(['user_code'=>$data['user_code']])
                    ->find();
        if(!empty($clinic_info)){
            $data['clinic_name']=$clinic_info['name'];
        }else{
             $this->error("未查询到该门店，请重试"); 
        }
        $clinic_info_me=Db::name('coupons_clinic')
                            ->where(['user_code'=>$data['user_code'],'user_id'=>array('eq',$data['user_id'])])
                            ->find();
        if(!empty($clinic_info_me)){
            $this->success("您已绑定该门店，正在跳转...");  
        }
        $clinic_info_bind=Db::name('coupons_clinic')
                            ->where(['user_code'=>$data['user_code'],'user_id'=>array('neq',0)])
                            ->find();
        if(!empty($clinic_info_bind)){
            $this->error("该门店已绑定管理员"); 
        }
        $datas['user_id']=$data['user_id'];
        $datas['user_password']=$data['user_password'];
        $datam['user_id']=$data['user_id'];
        $datam['user_name']=$data['user_name'];
        $datam['user_mobile']=$data['user_mobile'];
        $datam['clinic_id']=$clinic_info['id'];
        $datam['clinic_name']=$clinic_info['name'];
        $datam['createtime']=time();
        $datam['updatetime']=time();
        $datam['weigh']='';
        $datam['apply_statuslist']=1;

        $is_apply=Db::name('coupons_apply')->where(['user_id'=>$data['user_id'],'clinic_id'=>$clinic_info['id']])->count();
        //var_dump($is_apply);exit;
       if($is_apply==0){
          $resc=Db::name('coupons_apply')->insert($datam);
       }
        
        $res=Db::name('coupons_clinic')
            ->where(['user_code'=>$data['user_code']])
            ->update($datas);
         if($res){
            $this->success("门店绑定成功",$clinic_info); 
        }else{
            $this->error("绑定失败，请重试"); 
        }
    }
    
 /**
     * ==修改门店密码
     * @param string $user_code 门店编码
     * @param string $user_password 门店原密码
     * @param string $user_new_password 门店新密码
     */
    public function setClinicPassword(){
        
        $data=$this->request->request();
        if(!$data['user_code'] || !$data['user_password']){
           $this->error(__('Invalid parameters')); 
        }
        $data['user_id']=$this->auth->id;
        $clinic_info=Db::name('coupons_clinic')
                    ->where(['user_code'=>$data['user_code'],'user_id'=>$data['user_id']])
                    ->find();
        if(empty($clinic_info)){
           $this->error("您不是该门店管理员，无权限修改"); 
        }
        $clinic_info_confirm=Db::name('coupons_clinic')
                            ->where(['user_code'=>$data['user_code'],'user_password'=>$data['user_password']])
                            ->find();
        if(empty($clinic_info_confirm)){
            $this->error("原密码错误，请重新输入"); 
        }
        $datas['user_password']=$data['user_new_password'];
        $res=Db::name('coupons_clinic')
                            ->where(['user_code'=>$data['user_code']])
                            ->update($datas);
        
         if($res){
            $this->success("门店密码修改成功",$clinic_info); 
        }else{
            $this->error("门店密码修改失败，请重试"); 
        }
    }
    

    /**
     * ==我的消息列表
     * @param string $page 页数
     * @param string $limit   每页条数 
     * 
     */
      public function messages(){
        $page=$this->request->request('page');
        $limit=$this->request->request('limit');
        $notice=Db::name('record_log')->where('user_id',$this->user_id)->page($page,$limit)->order('createtime','desc')->select();
        foreach ($notice as $key => $value) {
          $notice[$key]['createtime']=date('Y-m-d H:i:s',$value['createtime']);
        }
        $this->success("success", ['data' => $notice]);
      }
    
      /**
     * ==过滤上传特殊表情符号的
     * @param $str
     * @return mixed
     */
    private function filter_emoji($str)
    {
        preg_match_all('/[\x{4e00}-\x{9fff}\d\w\s[:punct:]]+/u',$str,$result);
        return join('',$result[0]);
    }
 /**
     * ==三方接口,自动生成优惠券模块
    *
     * @param string $platform 平台，1代表HR员工系统，,2代表 积分商城
     * @param string $type     优惠券类型，对应后台优惠券类型id
     * @param string $num      生成同类型优惠券数量,默认是1
     * @param string $unionid  积分商城传此参数，唯一识别用户 
     * @param string $name     用户姓名，HR系统传此参数
     * @param string $staffNumber     员工工号，HR系统传此参数
     */
    public function createAutoCouponlists()
    {  
       
       $data=$this->request->request();
       $platform=isset($data['platform'])?intval($data['platform']):'';
       $type=isset($data['type'])?$data['type']:'';
       $name=isset($data['name'])?$data['name']:'';
       $num=isset($data['num'])?$data['num']:'';
       $staffnumber=isset($data['staffNumber'])?$data['staffNumber']:'';
       $unionid=isset($data['unionid'])?$data['unionid']:'';
       //var_dump($data);exit;
       if(!$platform){
           $this->error(__('Invalid parameters'));
       }
       //1代表HR员工系统 
       if($platform==1){
            if(!$type || !$name || !$num || !$staffnumber){
                $this->error(__('Invalid parameters'));
            }else{
                $result=$this->createAutoCoupon($platform,$type,$num,0,$name,$staffnumber);
            }
        //2代表积分商城系统
       }else if($platform==2){
            if(!$type || !$unionid || !$num){
                $this->error(__('Invalid parameters'));
            }else{
                $result=$this->createAutoCoupon($platform,$type,$num,$unionid);
            }
       }else{
            $this->error(__('平台类型错误'));
       }
  
       if($result){
            if($result['status'] && $result['status']==1){
                $this->success('ok',$result);
            }else{
               $this->error('fault',$result); 
            }
        }else{
           $this->error('优惠券创建失败，请重试');  
        }
    } 
    

}
